<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Qtcreator,TCP,UDP,">










<meta name="description" content="TCP 和 UDP 通信">
<meta name="keywords" content="Qtcreator,TCP,UDP">
<meta property="og:type" content="article">
<meta property="og:title" content="Qt实战（2）">
<meta property="og:url" content="http://Anzusen.com/2019/05/19/Qt实战（2）/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="TCP 和 UDP 通信">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/TCP_connect.jpg">
<meta property="og:image" content="http://anzusen.com/image/tcp_send_text.png">
<meta property="og:image" content="http://anzusen.com/image/UDP_imag.png">
<meta property="og:image" content="http://anzusen.com/image/udp_connect.png">
<meta property="og:image" content="http://anzusen.com/image/tcp_file.png">
<meta property="og:image" content="http://anzusen.com/image/tcp_sendfile.png">
<meta property="og:image" content="http://anzusen.com/image/chat_now.png">
<meta property="og:updated_time" content="2020-04-06T14:18:34.788Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Qt实战（2）">
<meta name="twitter:description" content="TCP 和 UDP 通信">
<meta name="twitter:image" content="http://anzusen.com/image/TCP_connect.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/05/19/Qt实战（2）/">





  <title>Qt实战（2） | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/05/19/Qt实战（2）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Qt实战（2）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-19T21:09:54+08:00">
                2019-05-19
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/QT界面/" itemprop="url" rel="index">
                    <span itemprop="name">QT界面</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/05/19/Qt实战（2）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/05/19/Qt实战（2）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.4k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  14
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="TCP-和-UDP-通信"><a href="#TCP-和-UDP-通信" class="headerlink" title="TCP 和 UDP 通信"></a>TCP 和 UDP 通信</h1><a id="more"></a>
<h2 id="TCP"><a href="#TCP" class="headerlink" title="TCP"></a>TCP</h2><p>  先通过一张图片了解TCP通信过程，QT的TCP Socket（套接字）通信仍然有服务端、客户端之分。图中左为客户端，右为服务端。服务端通过监听某个端口来监听是否有客户端连接到来，如果有连接到来，则建立<strong>新</strong>的SOCKET连接；客户端通过IP和PORT（端口）连接服务端，当成功建立连接之后，就可进行数据的接收和发送了。数据的收发是通过read()和write()来进行的。Socket，也就是常说的“套接字”。Socket简单地说，就是一个IP地址加一个port端口<br> TCP通信原理图<br><img src="/image/TCP_connect.jpg" alt="TCP通信原理图"></p>
<p>先来看运行结果：<br><img src="/image/tcp_send_text.png" alt></p>
<h3 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h3><ol>
<li>新建项目，选择Qt Widgets应用，项目名为TCP_connect,类名为ServerWidget。</li>
<li><p>在 TCP_connect.pro内联网，添加以下代码，添加后先编译不运行。（之后的所有有关UDP和CDP，<strong>都要加上这句</strong>，以后不再多说。）</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">QT       += core gui network</span><br><span class="line"></span><br><span class="line">CONFIG += C++<span class="number">11</span> <span class="comment">//之后可能会用到c++中的Lambdas表达式，所以把这句也加上</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>设计ui界面如生成结果中的服务端</p>
</li>
<li>在ServerWidget.h头文件中，添加头文件并，创建监听套接字和通信套接字对象。</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTcpServer&gt; //监听套接字</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTcpSocket&gt; //通信套接字</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    QTcpServer *tcpServer;<span class="comment">//监听套接字</span></span><br><span class="line">    QTcpSocket *tcpSocket;<span class="comment">//通信套接字</span></span><br></pre></td></tr></table></figure>
<ol start="5">
<li>在ServerWidget.h源文件构造函数添加以下</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">  setWindowTitle(<span class="string">"服务器：8888"</span>);</span><br><span class="line"></span><br><span class="line">  tcpServer=<span class="literal">NULL</span>;</span><br><span class="line">  tcpSocket=<span class="literal">NULL</span>;</span><br><span class="line">  <span class="comment">//监听套接字分配空间，父窗口自动回收空间</span></span><br><span class="line">  tcpServer=<span class="keyword">new</span> QTcpServer(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">//监听并绑定</span></span><br><span class="line">  tcpServer-&gt;listen(QHostAddress::Any,<span class="number">8888</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">//触发新连接</span></span><br><span class="line">  connect(tcpServer,&amp;QTcpServer::newConnection,</span><br><span class="line">          [=]()&#123;</span><br><span class="line">      <span class="comment">//取出建立好连接的套接字并赋值给通信套接字</span></span><br><span class="line">      tcpSocket =tcpServer-&gt;nextPendingConnection();<span class="comment">//取出下一个连接，即当前最近的一个连接</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">//获取对方的ip和端口(peer表示对方）</span></span><br><span class="line">      QString ip=tcpSocket-&gt;peerAddress().toString();<span class="comment">//.toIPv4Address()</span></span><br><span class="line">      qint16 port = tcpSocket-&gt;peerPort();</span><br><span class="line"></span><br><span class="line"><span class="comment">//连接成功</span></span><br><span class="line">      QString temp=QString(<span class="string">"[%1:%2]:成功连接"</span>).arg(ip).arg(port);</span><br><span class="line">      ui-&gt;textEditRead-&gt;setText(temp);<span class="comment">//显示到只读窗口</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">//接收数据</span></span><br><span class="line">      connect(tcpSocket,&amp;QTcpSocket::readyRead,</span><br><span class="line">              [=]()&#123;</span><br><span class="line">          <span class="comment">//从通信套接字中取出内容</span></span><br><span class="line">          QByteArray <span class="built_in">array</span>= tcpSocket-&gt;readAll();</span><br><span class="line">          ui-&gt;textEditRead-&gt;append(<span class="built_in">array</span>);</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>发送消息（文本）按钮和关闭连接按钮，分别右击转到槽。添加代码</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">void</span> ServerWidget::on_buttonsend_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span>(tcpSocket==<span class="literal">NULL</span>)&#123;<span class="comment">//有套接字连接的情况下，才能进行此操作</span></span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//获取write编辑区内容</span></span><br><span class="line">    QString str=ui-&gt;textEditWrite-&gt;toPlainText();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//给客服端发送数据，使用tcpSocket套接字</span></span><br><span class="line">    tcpSocket-&gt;write(str.toUtf8().data());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> ServerWidget::on_buttonclose_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span>(tcpSocket==<span class="literal">NULL</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//主动和客户端断开连接</span></span><br><span class="line">    tcpSocket-&gt;disconnectFromHost();<span class="comment">//从服务器取消这个连接到它的服务器</span></span><br><span class="line">    tcpSocket-&gt;close();</span><br><span class="line">    tcpSocket=<span class="literal">NULL</span>;<span class="comment">//断开连接后，通信套接字里面就没有内容了</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h3><p>1.右击项目，添加c++class类，类名为clientwidget。设计ui界面如生成结果。<br>2.在clientwidget.h头文件中添加代码,通信套接字头文件和对象。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTcpSocket&gt; //通信套接字</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    QTcpSocket *tcpsocket;<span class="comment">//通信套接字</span></span><br></pre></td></tr></table></figure>
<p>3.在clientwidget.cpp文件构造函数中添加代码,</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">setWindowTitle(<span class="string">"客户端"</span>);</span><br><span class="line"></span><br><span class="line">tcpsocket=<span class="literal">NULL</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//分配空间，指定父对象</span></span><br><span class="line">tcpsocket=<span class="keyword">new</span> QTcpSocket(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//连接到服务器就会触发connected转到槽</span></span><br><span class="line">connect(tcpsocket,&amp;QTcpSocket::connected,</span><br><span class="line">        [=]()&#123;</span><br><span class="line">            ui-&gt;textEditRead-&gt;setText(<span class="string">"成功和服务器建立好连接"</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">connect(tcpsocket,&amp;QTcpSocket::readyRead,</span><br><span class="line">        [=]()&#123;</span><br><span class="line">            <span class="comment">//获取对方发送的数据</span></span><br><span class="line">    QByteArray <span class="built_in">array</span>=tcpsocket-&gt;readAll();</span><br><span class="line">    <span class="comment">//显示到read编辑框中</span></span><br><span class="line">    ui-&gt;textEditRead-&gt;append(<span class="built_in">array</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>三个按钮分别右击转到槽</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QHostAddress&gt;//之后的操作要添加此头文件</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> ClientWidget::on_bottonSend_clicked()</span><br><span class="line">&#123;</span><br><span class="line">   <span class="comment">//获取write编辑框内容</span></span><br><span class="line">    QString str=ui-&gt;textEditWrite-&gt;toPlainText();</span><br><span class="line">    <span class="comment">//发送数据</span></span><br><span class="line">    tcpsocket-&gt;write(str.toUtf8().data());</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> ClientWidget::on_buttonConnect_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//从输入行编辑器获取服务器的ip和端口</span></span><br><span class="line">    QString ip=ui-&gt;lineEditIp-&gt;text();</span><br><span class="line">    qint16 port=ui-&gt;lineEditPort-&gt;text().toInt();<span class="comment">//qint16代表16位的无符号整形。</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//主动和服务器建立连接</span></span><br><span class="line">    tcpsocket-&gt;connectToHost(QHostAddress(ip),port);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> ClientWidget::on_bottonClose_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//主动和对方断开连接</span></span><br><span class="line">    tcpsocket-&gt;disconnectFromHost();</span><br><span class="line">    tcpsocket-&gt;close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="UDP"><a href="#UDP" class="headerlink" title="UDP"></a>UDP</h2><p>  UDP（User Datagram Protocol即用户数据报协议）是一个轻量级的，不可靠的，面向数据报的无连接协议。就像我们现在使用的QQ，其聊天时就是使用UDP协议进行消息发送的。像QQ那样，当有很多用户，发送的大部分都是短消息，要求能及时响应，并且对安全性要求不是很高的情况下使用UDP协议。即使偶尔丢失一两个数据包，也不会对接收结果产生太大影响。</p>
<p>   在Qt中提供了QUdpSocket 类来进行UDP数据报（datagrams）的发送(writeDatagram)和接收(readDatagram)。<br> 先来看一下UDP通信过程<br><img src="/image/UDP_imag.png" alt="udp通信原理图"></p>
<p>现在我们来创造下面如图所示的一个服务器：<br><img src="/image/udp_connect.png" alt="udp运行结果"><br>新建项目，选择Qt Widgets应用，项目名为udpsocket,类名为Widget。</p>
<ol>
<li>先根据上图设计界面</li>
<li>在头文件中添加通信套接字声明，再定义一个对象</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QUdpSocket&gt;</span></span></span><br><span class="line"></span><br><span class="line">QUdpSocket *udpsocket;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>分配空间和绑定端口,连接通信套接字自动触发readyRead()信号和处理的槽函数</li>
</ol>
<p>先在头文件声明公有槽函数：<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dealMag</span><span class="params">()</span></span>;<span class="comment">//槽函数，处理对方发送过来的信号。</span></span><br></pre></td></tr></table></figure></p>
<p>在构造函数添加：<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">Widget::Widget(QWidget *parent) :</span><br><span class="line">    QWidget(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::Widget)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    setWindowTitle(<span class="string">"服务端口为：8888"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//分配空间，指定父对象</span></span><br><span class="line">    udpsocket= <span class="keyword">new</span> QUdpSocket(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//绑定端口</span></span><br><span class="line">    udpsocket-&gt;bind(<span class="number">8888</span>);</span><br><span class="line">    <span class="comment">//udpsocket-&gt;bind(QHostAddress::AnyIPv4,8888);</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//加入某个组播</span></span><br><span class="line">    <span class="comment">//组播地址是D类地址</span></span><br><span class="line">    <span class="comment">//udpsocket-&gt;joinMulticastGroup(QHostAddress("244.0.0.2"));</span></span><br><span class="line">    <span class="comment">//udpsocket-&gt;leaveMulticastGroup(1);//退出组播</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//当对方成功发送数据过来</span></span><br><span class="line">    <span class="comment">//自动触发readyRead()信号</span></span><br><span class="line">    connect(udpsocket,&amp;QUdpSocket::readyRead,<span class="keyword">this</span>,&amp;Widget::dealMag);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">void</span> Widget::dealMag()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//读取对方发送的内容</span></span><br><span class="line">    <span class="keyword">char</span> buf[<span class="number">1024</span>]=&#123;<span class="number">0</span>&#125;;</span><br><span class="line">    QHostAddress clientAddr; <span class="comment">//对方地址</span></span><br><span class="line">    quint16 clientPort;  <span class="comment">//对方端口</span></span><br><span class="line">    qint64 len=udpsocket-&gt;readDatagram(buf,<span class="keyword">sizeof</span>(buf),&amp;clientAddr,&amp;clientPort);</span><br><span class="line">    <span class="keyword">if</span>(len&gt;<span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//接收内容格式化</span></span><br><span class="line">        QString str = QString(<span class="string">"[%1:%2] %3"</span>)</span><br><span class="line">                .arg(clientAddr.toString())</span><br><span class="line">                .arg(clientPort)</span><br><span class="line">                .arg(buf);</span><br><span class="line">        ui-&gt;textEdit-&gt;setText(str);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol start="4">
<li>两个按钮转到槽</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QHostAddress&gt;//记得添加这个头文件</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> Widget::on_bottonSend_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获取对方ip和端口</span></span><br><span class="line">    QString ip=ui-&gt;lineEditIP-&gt;text();</span><br><span class="line">    qint16 port=ui-&gt;lineEditPort-&gt;text().toInt();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取编辑区数据</span></span><br><span class="line">    QString str=ui-&gt;textEdit-&gt;toPlainText();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//给指定的ip发送数据</span></span><br><span class="line">    udpsocket-&gt;writeDatagram(str.toUtf8(),QHostAddress(ip),port);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> Widget::on_bottonClose_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//主动和对方断开连接</span></span><br><span class="line">    udpsocket-&gt;disconnectFromHost();</span><br><span class="line">    udpsocket-&gt;close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>根据以上方法就可以创建很多服务端（客户端），通过绑定的端口就可以相互通信了。</li>
</ol>
<h2 id="UDP组播问题"><a href="#UDP组播问题" class="headerlink" title="UDP组播问题"></a>UDP组播问题</h2><p>  因为在实际项目中，用户有N个电脑预览实时视频，如果同时有N多个终端去连接服务器，服务器的压力发送数据带宽的压力很大，所以给提出采用组播的方式去解决此类的问题。就像QQ群一样，限定人数，避免广播风暴。组播的原理大致就是服务器往某一组播地址和端口发数据，之后客户端从指定的组播地址和端口去取数据，好处就是减轻了服务器发送的压力</p>
<p>  开启多个服务器，用客户端发送数据，所有服务器端(复制的过程)都会收到客户端发送的数据。</p>
<p>组播实现在上个例子代码中注释部分有，需要<strong>注意</strong>：</p>
<ul>
<li>发送端既可以加入组播，也可以不加入组播；</li>
</ul>
<p>-吧服务端绑定的ip地址必须是ipv4地址；</p>
<ul>
<li>组播地址必须是D类地址</li>
</ul>
<h2 id="TCP传输文件"><a href="#TCP传输文件" class="headerlink" title="TCP传输文件"></a>TCP传输文件</h2><p>  先来看过传输文件程图：<br><img src="/image/tcp_file.png" alt="TCP传输文件运行结果图"><br>  运行结果：<br><img src="/image/tcp_sendfile.png" alt="TCP传输文件运行结果图"></p>
<p>首先看到运行结果如上图所示<br>新建项目，选择Qt Widgets应用，项目名为tcpfile,类名为ServerWidget。</p>
<h3 id="服务端-1"><a href="#服务端-1" class="headerlink" title="服务端"></a>服务端</h3><ol>
<li>根据运行结果设计界面.</li>
<li>ServerWidget.h</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> SERVERWIDGET_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> SERVERWIDGET_H</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;QWidget&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTcpServer&gt;//监听套接字</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTcpSocket&gt;//通信套接字</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QFile&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTimer&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> Ui &#123;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ServerWidget</span>;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ServerWidget</span> :</span> <span class="keyword">public</span> QWidget</span><br><span class="line">&#123;</span><br><span class="line">    Q_OBJECT</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">explicit</span> <span class="title">ServerWidget</span><span class="params">(QWidget *parent = <span class="number">0</span>)</span></span>;</span><br><span class="line">    ~ServerWidget();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">sendData</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> slots:</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">on_buttonfile_clicked</span><span class="params">()</span></span>;<span class="comment">//这是转到槽自动添加的</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">on_buttonsend_clicked</span><span class="params">()</span></span>;<span class="comment">//这是转到槽自动添加的</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    Ui::ServerWidget *ui;</span><br><span class="line">    QTcpServer *tcpserver;<span class="comment">//通信套接字和</span></span><br><span class="line">    QTcpSocket *tcpsocket;<span class="comment">//监听套接字</span></span><br><span class="line"></span><br><span class="line">    QFile file;<span class="comment">//文件对象</span></span><br><span class="line">    QString filename;<span class="comment">//文件名字</span></span><br><span class="line">    qint64 filesize;<span class="comment">//文件大小</span></span><br><span class="line">    qint64 sendsize;<span class="comment">//已经发送文件大小</span></span><br><span class="line">    QTimer timer;<span class="comment">//定时器</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span> <span class="comment">// SERVERWIDGET_H</span></span></span><br></pre></td></tr></table></figure>
<ol start="3">
<li><p>ServerWidget.cpp中添加代码</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"serverwidget.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"ui_serverwidget.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QFileDialog&gt;//文件对话框</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QDebug&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QFileInfo&gt;</span></span></span><br><span class="line"></span><br><span class="line">ServerWidget::ServerWidget(QWidget *parent) :</span><br><span class="line">    QWidget(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::ServerWidget)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    setWindowTitle(<span class="string">"服务器端口:8888"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//分配空间</span></span><br><span class="line">    tcpserver = <span class="keyword">new</span> QTcpServer(<span class="keyword">this</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//监听</span></span><br><span class="line">    tcpserver-&gt;listen(QHostAddress::Any,<span class="number">8888</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//没建立连接前是不能对进行操作的</span></span><br><span class="line">    ui-&gt;buttonfile-&gt;setEnabled(<span class="literal">false</span>);</span><br><span class="line">    ui-&gt;buttonsend-&gt;setEnabled(<span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//自动触发newconnection</span></span><br><span class="line">    connect(tcpserver,&amp;QTcpServer::newConnection,</span><br><span class="line">    [=]()</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//取出建立好的连接套接字,获取ip和端口</span></span><br><span class="line">        tcpsocket = tcpserver-&gt;nextPendingConnection();</span><br><span class="line">        QString ip = tcpsocket-&gt;peerAddress().toString();</span><br><span class="line">        quint16 port = tcpsocket-&gt;peerPort();<span class="comment">//无符号的</span></span><br><span class="line">        <span class="comment">//格式化并显示在文本编辑框中</span></span><br><span class="line">        QString str = QString(<span class="string">"[%1；%2] 连接成功！"</span>).arg(ip).arg(port);</span><br><span class="line">        ui-&gt;textEdit-&gt;setText(str);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//连接成功后，才能发送文件</span></span><br><span class="line">        ui-&gt;buttonfile-&gt;setEnabled(<span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">       &#125;);</span><br><span class="line">     connect(&amp;timer,&amp;QTimer::timeout,</span><br><span class="line">                [=]()</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">//关闭定时器</span></span><br><span class="line">            timer.stop();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//发送文件</span></span><br><span class="line">            sendData();</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> ServerWidget::sendData()</span><br><span class="line">&#123;</span><br><span class="line">    qint64 len=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">do</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//每次发送数据的大小</span></span><br><span class="line">        <span class="keyword">char</span> buf[<span class="number">4</span>*<span class="number">1024</span>]=&#123;<span class="number">0</span>&#125;;<span class="comment">//每次发4k</span></span><br><span class="line">        len=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//往文件中读数据</span></span><br><span class="line">        len = file.read(buf,<span class="keyword">sizeof</span>(buf));</span><br><span class="line">        <span class="comment">//发送数据，读多少发多少</span></span><br><span class="line">        len = tcpsocket-&gt;write(buf,len);<span class="comment">//数据和最大大小</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//发送数据需要累加</span></span><br><span class="line">        sendsize += len;</span><br><span class="line">    &#125;<span class="keyword">while</span>(len &gt; <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//是否文件发送完毕</span></span><br><span class="line">    <span class="keyword">if</span>(sendsize == filesize)</span><br><span class="line">    &#123;</span><br><span class="line">        ui-&gt;textEdit-&gt;append(<span class="string">"文件发送完毕"</span>);</span><br><span class="line"></span><br><span class="line">        file.close();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//把客户端断开</span></span><br><span class="line">        tcpsocket-&gt;disconnectFromHost();</span><br><span class="line">        tcpsocket-&gt;close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>按钮转到槽函数</p>
</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> ServerWidget::on_buttonfile_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获取打开文件路径</span></span><br><span class="line">    QString filePath = QFileDialog::getOpenFileName(<span class="keyword">this</span>,<span class="string">"open"</span>,<span class="string">"../"</span>);</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">false</span> == filePath.isEmpty())<span class="comment">//选择路径有效</span></span><br><span class="line">    &#123;</span><br><span class="line">        filename.clear();</span><br><span class="line">        filesize = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//通过路径获取文件信息（文件名和文件大小）</span></span><br><span class="line">        <span class="function">QFileInfo <span class="title">info</span><span class="params">(filePath)</span></span>;<span class="comment">//构造对象</span></span><br><span class="line">        filename = info.fileName();</span><br><span class="line">        filesize = info.size();<span class="comment">//qint64</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//已经发送大小还为0</span></span><br><span class="line">        sendsize=<span class="number">0</span>;</span><br><span class="line">        <span class="comment">//只读方式打开文件</span></span><br><span class="line">        <span class="comment">//指定文件名字</span></span><br><span class="line">        file.setFileName(filePath);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//打开文件</span></span><br><span class="line">        <span class="keyword">bool</span> isok = file.open(QIODevice::ReadOnly);</span><br><span class="line">        <span class="keyword">if</span>(<span class="literal">false</span> == isok)</span><br><span class="line">        &#123;</span><br><span class="line">            qDebug()&lt;&lt;<span class="string">"只读方式打开文件失败 98"</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//提示打开的文件路径</span></span><br><span class="line">        ui-&gt;textEdit-&gt;append(filePath);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//打开文件后，按钮的状态</span></span><br><span class="line">        ui-&gt;buttonfile-&gt;setEnabled(<span class="literal">false</span>);</span><br><span class="line">        ui-&gt;buttonsend-&gt;setEnabled(<span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        qDebug()&lt;&lt;<span class="string">"选择文件路径出错"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> ServerWidget::on_buttonsend_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//先发送文件头信息  文件名##文件大小</span></span><br><span class="line">    QString head = QString(<span class="string">"%1##%2"</span>).arg(filename).arg(filesize);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//发送头部信息</span></span><br><span class="line">    qint64 len = tcpsocket-&gt;write(head.toUtf8());</span><br><span class="line">    <span class="keyword">if</span>(len &gt; <span class="number">0</span>)<span class="comment">//头部信息发送成功</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//发送真正的文件信息</span></span><br><span class="line">        <span class="comment">//防止tcp黏包文件</span></span><br><span class="line">        <span class="comment">//需要通过定时器</span></span><br><span class="line">        timer.start(<span class="number">20</span>);<span class="comment">//定时器开始就会自动触发timeout信号</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        qDebug()&lt;&lt;<span class="string">"头部信息发送失败"</span>;</span><br><span class="line">        file.close();</span><br><span class="line">        ui-&gt;buttonfile-&gt;setEnabled(<span class="literal">true</span>);</span><br><span class="line">        ui-&gt;buttonsend-&gt;setEnabled(<span class="literal">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="客户端-1"><a href="#客户端-1" class="headerlink" title="客户端"></a>客户端</h3><ol>
<li>右击添加，class c++新文件，类名为clientwidget.设计界面</li>
<li>clientwidget.h中添加代码</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QFile&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QTimer&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> Ui &#123;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ServerWidget</span>;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ServerWidget</span> :</span> <span class="keyword">public</span> QWidget</span><br><span class="line">&#123;</span><br><span class="line">    Q_OBJECT</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">explicit</span> <span class="title">ServerWidget</span><span class="params">(QWidget *parent = <span class="number">0</span>)</span></span>;</span><br><span class="line">    ~ServerWidget();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">sendData</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> slots:</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">on_buttonfile_clicked</span><span class="params">()</span></span>;<span class="comment">//这是转到槽自动添加的</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">on_buttonsend_clicked</span><span class="params">()</span></span>;<span class="comment">//这是转到槽自动添加的</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    Ui::ServerWidget *ui;</span><br><span class="line">    QTcpServer *tcpserver;<span class="comment">//通信套接字和</span></span><br><span class="line">    QTcpSocket *tcpsocket;<span class="comment">//监听套接字</span></span><br><span class="line"></span><br><span class="line">    QFile file;<span class="comment">//文件对象</span></span><br><span class="line">    QString filename;<span class="comment">//文件名字</span></span><br><span class="line">    qint64 filesize;<span class="comment">//文件大小</span></span><br><span class="line">    qint64 sendsize;<span class="comment">//已经发送文件大小</span></span><br><span class="line">    QTimer timer;<span class="comment">//定时器</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span> <span class="comment">// SERVERWIDGET_H</span></span></span><br></pre></td></tr></table></figure>
<ol start="3">
<li>clientwidget.cpp中添加代码</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"clientwidget.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"ui_clientwidget.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QDebug&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QMessageBox&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QHostAddress&gt;</span></span></span><br><span class="line"></span><br><span class="line">clientWidget::clientWidget(QWidget *parent) :</span><br><span class="line">    QWidget(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::clientWidget)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    setWindowTitle(<span class="string">"客户端"</span>);</span><br><span class="line"></span><br><span class="line">    tcpsocket = <span class="keyword">new</span> QTcpSocket(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//ui-&gt;progressBar-&gt;setValue(0);//当前值</span></span><br><span class="line"></span><br><span class="line">    isstart = <span class="literal">true</span>;<span class="comment">//用来判断接受的是不是头部</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//连接成功准备接收文件</span></span><br><span class="line">    connect(tcpsocket,&amp;QTcpSocket::readyRead,</span><br><span class="line">            [=]()</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//取出接受的内容</span></span><br><span class="line">        QByteArray buf = tcpsocket-&gt;readAll();</span><br><span class="line">        <span class="keyword">if</span>(<span class="literal">true</span> == isstart)<span class="comment">//第一次发的头，接收头</span></span><br><span class="line">        &#123;</span><br><span class="line">            isstart = <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//取出接收的内容(拆包)</span></span><br><span class="line">            filename = QString(buf).section(<span class="string">"##"</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br><span class="line">            filesize = QString(buf).section(<span class="string">"##"</span>,<span class="number">1</span>,<span class="number">1</span>).toInt();</span><br><span class="line">            <span class="comment">//开始收到的文件大小为0</span></span><br><span class="line">            receivesize=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//打开文件</span></span><br><span class="line">            file.setFileName(filename);</span><br><span class="line">            <span class="keyword">bool</span> isok=file.open(QIODevice::WriteOnly);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span>(<span class="literal">false</span> == isok)</span><br><span class="line">            &#123;</span><br><span class="line">                qDebug()&lt;&lt;<span class="string">"writeonly error"</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">else</span><span class="comment">//取出文件数据</span></span><br><span class="line">         &#123;</span><br><span class="line">                qint64 len = file.write(buf);</span><br><span class="line">                receivesize += len;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span>(receivesize==filesize)<span class="comment">//文件接受完成</span></span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="comment">//给服务器发送接收完成信息</span></span><br><span class="line">                    tcpsocket-&gt;write(<span class="string">"file done"</span>);</span><br><span class="line"></span><br><span class="line">                    QMessageBox::information(<span class="keyword">this</span>,<span class="string">"完成"</span>,<span class="string">"文件接受完成！"</span>);</span><br><span class="line"></span><br><span class="line">                    tcpsocket-&gt;disconnectFromHost();<span class="comment">//断开连接</span></span><br><span class="line">                    tcpsocket-&gt;close();</span><br><span class="line">                &#125;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>按钮转到槽</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> clientWidget::on_bottonconnect_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获取服务器的ip和端口</span></span><br><span class="line">    QString ip=ui-&gt;lineEditip-&gt;text();</span><br><span class="line">    quint16 port = ui-&gt;lineEditport-&gt;text().toInt();</span><br><span class="line"></span><br><span class="line">    tcpsocket-&gt;connectToHost(QHostAddress(ip),port);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>主函数添加为：</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">"serverwidget.h"</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;QApplication&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">"clientwidget.h"</span></span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc, <span class="keyword">char</span> *argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function">QApplication <span class="title">a</span><span class="params">(argc, argv)</span></span>;</span><br><span class="line">    ServerWidget w;</span><br><span class="line">    w.show();</span><br><span class="line"></span><br><span class="line">    clientWidget w2;</span><br><span class="line">    w2.show();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> a.exec();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="心得"><a href="#心得" class="headerlink" title="心得"></a>心得</h2><p>  在学完上面的四个知识后，我写了一个实现两个pc机之间互相通信的程序，一个简单的聊天室，运行结果如下图，另一端改变绑定端口即可，使用的UDP协议，可以实现发文字消息和传输文件（文件对方接收后可以直接创建，但只能写一部分进去，我一直以为是文件写入有问题，后来才找出是我发文件的这一端发送文件大小小于实际文件大小，然后拖着拖着就难得去改了（优秀）），里面最大的问题是判断你接受的是文件还是文字问题，然后我用了分片（section）加关键字（file 和 text）区分。之后我会把我的代码上传到码云，这里不再说明过程。</p>
<p><img src="/image/chat_now.png" alt="TCP传输文件运行结果图"></p>
<p>项目地址：<a href="https://gitee.com/anzhusen/chatNow/tree/master/chatNow" target="_blank" rel="noopener">聊天室源码</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Qtcreator/" rel="tag"># Qtcreator</a>
          
            <a href="/tags/TCP/" rel="tag"># TCP</a>
          
            <a href="/tags/UDP/" rel="tag"># UDP</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/06/Qt实战（1）/" rel="next" title="Qt实战（1）">
                <i class="fa fa-chevron-left"></i> Qt实战（1）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/05/26/Qt实战（3）/" rel="prev" title="Qt实战（3）">
                Qt实战（3） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#TCP-和-UDP-通信"><span class="nav-number">1.</span> <span class="nav-text">TCP 和 UDP 通信</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#TCP"><span class="nav-number">1.1.</span> <span class="nav-text">TCP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端"><span class="nav-number">1.1.1.</span> <span class="nav-text">服务端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端"><span class="nav-number">1.1.2.</span> <span class="nav-text">客户端</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UDP"><span class="nav-number">1.2.</span> <span class="nav-text">UDP</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#UDP组播问题"><span class="nav-number">1.3.</span> <span class="nav-text">UDP组播问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TCP传输文件"><span class="nav-number">1.4.</span> <span class="nav-text">TCP传输文件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务端-1"><span class="nav-number">1.4.1.</span> <span class="nav-text">服务端</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端-1"><span class="nav-number">1.4.2.</span> <span class="nav-text">客户端</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#心得"><span class="nav-number">1.5.</span> <span class="nav-text">心得</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
